from django.shortcuts import render
from django.http import HttpResponse
from django.core.urlresolvers import reverse

# Create your views here.
from .. import models
from . viewsIndex import uploads
import os



def goodsindex(request):
    # 查询
    data=models.Goods.objects.filter().exclude(status=2)



    # 获取请求参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否右搜索条件
    if types:
        if types == 'title':
            # 按标题搜索
            data = data.filter(title__contains=keywords)
        elif types == 'price':

            # 获取价格区间
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        elif types == 'status':
            arr = {'新品': 0, '热卖': 1, '下架': 2}
            data = data.filter(status=arr[keywords])



    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(data, 10)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p', 1)
    # 获取当前页的数据
    goodslist = paginator.page(p)

    context={'goodslist':goodslist}
    return render(request,'myadmin/goods/index.html',context)


# 商品添加
def goodsadd(request):
    data=models.Cates.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')
    context={'cateslist':data}
    return render(request,'myadmin/goods/add.html',context)

# 执行商品添加
def goodsinsert(request):
    data=request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    data['cateid']=models.Cates.objects.get(id=data['cateid'])
    # 处理上传的商品主图
    myfile = request.FILES.get('pic_url')
    if myfile:
        data['pic_url'] = uploads(myfile)
    else:
        return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')

    # 执行数据的添加
    ob = models.Goods(**data)
    ob.save()
    return HttpResponse('<script>alert("添加成功");location.href="' + reverse('myadmin_goods_index') + '"</script>')

def goodsdel(request,uid):
    try:
        ob=models.Goods.objects.get(id=uid)
        ob.status=2
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')




# 商品编辑
def goodsedit(request):
    # 获取传递的商品id
    gid = request.GET.get('gid')
    # 获取商品数据对象
    ob = models.Goods.objects.get(id=gid)

    if request.method == 'GET':
        # 获取所有的商品分类数据
        cateslist = models.Cates.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')

        # 分配数据
        context = {'ginfo': ob, 'cateslist': cateslist}

        # 加载模板
        return render(request, 'myadmin/goods/edit.html', context)
    else:
        try:
            # 执行更新
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')

            # 修改对象的数据
            ob.cateid = models.Cates.objects.get(id=data['cateid'])
            # 判断是否上传了新的图片
            myfile = request.FILES.get('pic_url')
            if myfile:
                try:
                    # 删除旧图
                    os.remove(BASE_DIR + ob.pic_url)
                except:
                    pass
                # 上传新的图片,更新数据
                ob.pic_url = uploads(myfile)
            ob.title = data['title']
            ob.price = data['price']
            ob.store = data['store']
            ob.info = data['info']
            ob.save()
            return HttpResponse('<script>alert("更新成功");location.href="' + reverse('myadmin_goods_index') + '"</script>')
        except:
            return HttpResponse('<script>alert("更新失败");history.back(-1);"</script>')